<?php

namespace Phones\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller,
    Symfony\Component\HttpFoundation\Response;

abstract class AppController extends Controller {

    public function render($view = null, array $params = array(), Response $response = null) {
        if ($view === null) {
            $view = $this->getDefaultView();
        }

        $params = array_merge( $params, array(
            'brands' => $this->allBrands()
        ));
        return parent::render($view, $params, $response);
    }

    protected function getEntity($name) {
        return $this->getDoctrine()
                    ->getManager()
                    ->getRepository("PhonesMainBundle:{$name}");
    }

    private function allBrands($orderBy = 'Brand.name') {
        return $this->getEntity('Brand')
             ->find(array(
                'order' => $orderBy
             ));
    }

    protected function getDefaultView() {
        preg_match_all('/.+\\\\(.+?)Controller::(.+?)Action$/', $this->getRequest()->get('_controller'), $matches);
        $controller = $matches[1][0];
        $action     = $matches[2][0];
        
        return "PhonesMainBundle:{$controller}:{$action}.html.twig";
    }
}